package com.dc.filter;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dc.constat.SystemConstant;
import com.dc.util.JwtUtils;
import com.dc.vo.SysUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthFilter.class);

    @Value("${auth.skip.urls}")
    private String[] skipAuthUrls;

    @Value("${jwt.blacklist.key.format}")
    private String jwtBlacklistKeyFormat;

    @Autowired
    private RedisTemplate redisTemplate;

    final String UNCHECKTOKEN = "uncheck:";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();

        String url = exchange.getRequest().getURI().getPath();
        if (url.contains("/v2/api-docs")) {
            return chain.filter(exchange);
        }

        if (StrUtil.isNotBlank(url) && url.startsWith("/dc-control-system/websocket")) {
            return chain.filter(exchange);
        }
        if (StrUtil.isNotBlank(url) && url.startsWith("/dc-control-base/websocket")) {
            return chain.filter(exchange);
        }

        //给后续服务设置真实ip
        setHeadIp(exchange);

        if (Arrays.asList(skipAuthUrls).contains(url)) {

            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");

        //跳过不需要验证的路径
        //redisTemplate 获取不需要校验的路径
        Object object = redisTemplate.opsForValue().get(UNCHECKTOKEN + url);
        if (object != null && object instanceof String) {
            String s = String.valueOf(object);
            if (s.equals("\"" + url + "\"")) {
                return chain.filter(exchange);
            }
        }

        // 验证 token
        String verifyToken = JwtUtils.verifyToken(token, JwtUtils.getAudience(token));
        if ("500".equals(verifyToken)) {
            originalResponse.setStatusCode(HttpStatus.OK);
            originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            byte[] response = "{\"code\": 401,\"msg\": \"401 Illegal token.\"}"
                    .getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
            return originalResponse.writeWith(Flux.just(buffer));
        }
        //取出token包含的身份
        Map<String, Object> map = verifyUserToken(token);
        Object userName = map.get("userName");
        Object userId = map.get("userId");
        Object userInfo = map.get("userInfo");
        //跳过不需要验证的路径


        //从请求头中取出token
        //未携带token或token在黑名单内
        if (token == null || token.isEmpty() || isBlackToken(token)) {
            originalResponse.setStatusCode(HttpStatus.OK);
            originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            byte[] response = "{\"code\": 401,\"msg\": \"401 Unauthorized.\"}"
                    .getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
            return originalResponse.writeWith(Flux.just(buffer));
        }


        if (null == userId) {
            originalResponse.setStatusCode(HttpStatus.OK);
            originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            byte[] response = "{\"code\": 401,\"msg\": \"invalid token.\"}"
                    .getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
            return originalResponse.writeWith(Flux.just(buffer));
        }
        //将现在的request，添加当前身份
        ServerHttpRequest mutableReq = null;
        mutableReq = exchange.getRequest().mutate().header("Authorization-UserId", String.valueOf(userId)).header("token", token).build();
        ServerHttpRequest UserInfo = exchange.getRequest().mutate().header("Authorization-UserInfo", JSON.toJSONString(userInfo)).header("token", token).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).request(UserInfo).build();
        return chain.filter(mutableExchange);
    }

    private void setHeadIp(ServerWebExchange exchange) {
        try {
            String ipAddress = exchange.getRequest().getHeaders().getFirst("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = exchange.getRequest().getHeaders().getFirst("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = exchange.getRequest().getHeaders().getFirst("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = exchange.getRequest().getRemoteAddress().getHostString();
                if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {

                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
            if (StrUtil.isNotBlank(ipAddress)) {
                exchange.getRequest().mutate().header("TRUE-IP", String.valueOf(ipAddress)).build();
            }
        } catch (Exception exception) {
            LOGGER.error("ip获取失败");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * Redis存放路径
     */
    public final String redisKey = "token:";

    /**
     * JWT验证
     *
     * @param token
     * @return userName
     */
    private Map<String, Object> verifyUserToken(String token) {
        Map<String, Object> result = new HashMap<>();
//        try {
        String tokenRedisKey = this.redisKey + token;
        Map<String, Object> map = this.redisTemplate.opsForHash().entries(tokenRedisKey);
        // Redis中会话的用户类型
        Object userType = map.get(SystemConstant.REDIS_USER_TYPE_KEY);
        // Redis中会话的用户信息对象
        Object userInfo = map.get(SystemConstant.REDIS_USER_INFO_KEY);
        if (SystemConstant.REDIS_SYS_USER_TYPE.equals(userType)) {
            // 后台管理员用户
            if (userInfo instanceof SysUserVO) {
                SysUserVO sysUser = (SysUserVO) userInfo;
                result.put("userId", sysUser.getId());
                result.put("userInfo", sysUser);
                result.put("userName", sysUser.getUserName());
                return result;
            }
        }
        return result;
//        } catch (Exception exception) {
//            LOGGER.error("用户转换错误", exception.getMessage());
//            return result;
//        }

    }


    /**
     * 判断token是否在黑名单内
     *
     * @param token
     * @return
     */
    private boolean isBlackToken(String token) {
        assert token != null;
        return redisTemplate.hasKey(String.format(jwtBlacklistKeyFormat, token));
    }
}
